package com.yvan.serverless;

import com.yvan.serverless.jdbc.*;
import com.yvan.serverless.script.ScriptService;
import com.yvan.serverless.utils.FileUtilExt;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.*;
import org.springframework.http.CacheControl;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.concurrent.TimeUnit;

@EnableAspectJAutoProxy
@Configuration
@ConditionalOnProperty(name = "serverless.typescript.url")
@EnableConfigurationProperties(ServerLessProperties.class)
@Slf4j
public class ServerLessAutoConfiguration {
    @Autowired
    public ServerLessProperties properties;

    @Bean
    public ServerLessServlet serverLessServlet() {
        return new ServerLessServlet();
    }

    @Bean
    public ScriptService scriptService() {
        return new ScriptService(properties);
    }

    @Bean
    public DaoResultTransformService daoResultTransform() {
        return new DaoResultTransformService();
    }

    @Bean
    public DaoFunctions daoFunctions() {
        return new DaoFunctions();
    }

    @Bean
    @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE, proxyMode = ScopedProxyMode.TARGET_CLASS)
    public TransactionService transactionService() {
        return new TransactionService();
    }

    /**
     * 注册 Servlet
     */
    @Bean
    public ServletRegistrationBean<ServerLessServlet> getServlet1() {
        String url = properties.getTypescript().getUrl() + "/*";
        log.info("\r\n================================\r\n= ServerLess \"{}\"\r\n================================", url);
        return new ServletRegistrationBean(serverLessServlet(), url);
    }

    /**
     * 注册 client 静态资源服务
     */
    @Bean
    public WebMvcConfigurer webMvcConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addResourceHandlers(ResourceHandlerRegistry registry) {
                if (properties.getClient() == null) {
                    return;
                }
                for (var entry : properties.getClient()) {
                    String url = entry.getUrl();
                    String path = normLocation(entry.getLocation());
                    ResourceHandlerRegistration handle = registry.addResourceHandler(url)
                            .addResourceLocations(path);

                    if ("true".equalsIgnoreCase(entry.getCache())) {
                        handle.setCacheControl(CacheControl.maxAge(30, TimeUnit.DAYS));
                    } else {
                        handle.setCacheControl(CacheControl.noStore());
                    }

                    log.info("ResourceHandler: {} ==> {}", url, path);
                }
            }
        };
    }

    private String normLocation(String location) {
        String path = FileUtilExt.normalizePath(location);
        if (!path.startsWith("file:")) {
            path = "file:" + path;
        }
        if (!path.endsWith("/")) {
            path = path + "/";
        }
        return path;
    }

    //结果集转换 begin
    @Bean
    public TimestampConvert timestampConvert() {
        return new TimestampConvert();
    }

    @Bean
    public StringNullConvert stringNullConvert() {
        return new StringNullConvert();
    }
    //结果集转换 end
}
